package com.sd.projectinterface;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Application;

@SuppressLint("ParserError")
public class Login extends Activity{
	
	EditText un, pw;
	Button bt;
	TextView mes;
	
	public static final String KEY_121 = "http://10.0.2.2/mathRomp/loginTest.php";
	
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
		 	super.onCreate(savedInstanceState);
	        setContentView(R.layout.login); 
	        un = (EditText) findViewById(R.id.username);
	        pw = (EditText) findViewById(R.id.password);
	        bt = (Button) findViewById(R.id.login);
	        mes = (TextView) findViewById(R.id.message);
	        
	        bt.setOnClickListener(new View.OnClickListener(){
				@SuppressLint("ParserError")
				public void onClick(View v) {
					
					JSONObject jsonData = getServerData(KEY_121);
					if(jsonData != null){
						String p;
						try {
							p = jsonData.getString("password");
							if(p.equals(pw.getText()+"")){
								MyApplication myApp = (MyApplication) getApplicationContext();
								myApp.setUser(jsonData.getInt("userId"), jsonData.getString("username"),
										jsonData.getInt("totalScore"), jsonData.getInt("fastestTime"));
								Intent i = new Intent(Login.this, MainActivity.class);
								i.putExtra("j", jsonData.getInt("userId"));
								startActivity(i);
							}else{
								mes.setText("Incorrect password");
							}
			 			} catch (JSONException e) {
							mes.setText("Username not valid");
							e.printStackTrace();
						}
					}else{
						mes.setText("Username not valid");
					}
				}
	        });
	 	}
	 
	 @SuppressLint("ParserError")
	public JSONObject getServerData(String returnString){
	    	InputStream is = null;
	    	String result = "";
	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	    	nameValuePairs.add(new BasicNameValuePair("userName", un.getText()+""));
	    	
	    	//http post
	    	try{
	    		HttpClient httpclient = new DefaultHttpClient();
	    		HttpPost httppost = new HttpPost(KEY_121);
	    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    		HttpResponse response = httpclient.execute(httppost);
	    		HttpEntity entity = response.getEntity();
	    		is = entity.getContent();
	    	}catch(Exception e){
	    		mes.setText("Username not valid");
	    		Log.e("log_tag", "Error in http connection: "+e);
	    		return null;
	    	}
	    	
	    	//convert response to string
	    	try{
	    		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
	    		StringBuilder sb = new StringBuilder();
	    		String line = null;
	    		while((line = reader.readLine()) != null){
	    			sb.append(line + "\n");
	    		}
	    		is.close();
	    		result = sb.toString();
	    		System.out.println(result);
	    	}catch(Exception e){
	    		mes.setText("Username not valid");
	    		Log.e("log_tag", "Error converting result: "+e);
	    		return null;
	    	}
	    	
	    	//parse json data
	    	JSONObject jObject = null;
	    	try{
	    		JSONArray jArray = new JSONArray(result);
	    		/*for(int i=0; i<jArray.length(); i++){
	    			JSONObject json_data = jArray.getJSONObject(i);
	    			Log.i("log_tag","id: "+json_data.getInt("userId")+
	    					", name: "+json_data.getString("username")+
	    					", password: "+json_data.getString("password")+
	    					", email: "+json_data.getString("email")+
	    					", userType: "+json_data.getInt("userType")+
	    					", totalScore: "+json_data.getInt("totalScore")
	    			);
	    			//Get an output to the screen
	    			returnString += "\n\t" + jArray.getJSONObject(i);
	    		}*/
	    		jObject = jArray.getJSONObject(0);
	    	}catch(JSONException e){
	    		mes.setText("Username not valid");
	    		Log.e("log_tag", "Error parsing data: "+e);
	    		return null;
	    	}
	    	return jObject;
	    }
}
